package com.actor;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Dmitry
 */
public class QueueThreadPool {

    private final List<QueueProcessor> queueProcessor = new ArrayList<>();

    public QueueThreadPool() {
        init(4);
    }

    public QueueThreadPool(int threadsCount) {
        if (threadsCount == 0) {
            throw new IllegalArgumentException("ThreadPool cannot have 0 threadsCount");
        }
        init(threadsCount);
    }

    private void init(int threadsCount) {
        for (int i = 0; i < threadsCount; i++) {
            QueueProcessor qp = new QueueProcessor();
            queueProcessor.add(qp);
            qp.start();
        }
    }

    public void addToPool(Actor actor) {
        QueueProcessor bestQueue = queueProcessor.get(0);
        int best = bestQueue.size();
        for (int i = 1; i < queueProcessor.size(); i++) {
            QueueProcessor processor = queueProcessor.get(i);
            if (best > processor.size()) {
                bestQueue = processor;
                best = processor.size();
            }
        }
        bestQueue.addActor(actor);
    }

    public void removeFormPool(Actor actor) {
        for (QueueProcessor processor : queueProcessor) {
            if (processor.hasActor(actor)) {
                processor.removeActor(actor);
                return;
            }
        }
    }

    public void stop() {
        for (QueueProcessor processor : queueProcessor) {
            processor.stop();
        }
    }
}
